package com.googlecode.stockhamster.aiholder;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.googlecode.stockhamster.Constant;
import com.googlecode.stockhamster.arbiter.IArbiter;
import com.googlecode.stockhamster.bank.IBank;
import com.googlecode.stockhamster.client.console.RumorDispatcher;
import com.googlecode.stockhamster.utils.XFireStub;

public class AIHolder {
	private IArbiter arbiter;
	private IBank bank;
	private AIEnvironment env;

	private List<AI> ai;

	public AIHolder() throws MalformedURLException {
		arbiter = new XFireStub<IArbiter>(Constant.arbiterUrl, IArbiter.class)
				.getStub();
		bank = new XFireStub<IBank>(Constant.bankUrl, IBank.class).getStub();
		ai = new ArrayList<AI>();
		env = new AIEnvironment();
	}

	public void readFile(String fileName) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(fileName));
		String line;

		while ((line = br.readLine()) != null) {
			String items[] = line.split(",");
			if (items.length == 6)
				ai.add(new AI(items[0], items[1], Integer.valueOf(items[2]),
						Integer.valueOf(items[3]), Integer.valueOf(items[4]),
						Integer.valueOf(items[5])));
		}
	}

	private void initAi() {
		for (AI a : ai) {
			if (arbiter.login(a.getUsername(), a.getPassword()) == null) {
				if (arbiter.open(a.getUsername(), a.getPassword()))
					bank.setMoney(Constant.bankAdminCode, a.getUsername(),
							Constant.aiInitialBalance);
				else
					a.setValid(false);
			}
			a.setArbiter(arbiter);
		}
	}

	public void refresh() {
		env.RefreshAll();
	}

	public void pick() {
		AI a = ai.get(new Random().nextInt(ai.size()));
		System.out.println("Running AI: " + a.getUsername());
		env.RefreshPrice();
		try {
			a.work(env);
		} catch (RuntimeException e) {
			System.err.println("Meet runtime exception.");
		}
	}

	public static void main(String args[]) throws IOException,
			InterruptedException {
		AIHolder holder = new AIHolder();
		RumorDispatcher dispather = new RumorDispatcher();

		holder.readFile(Constant.pathFileCSV);
		holder.initAi();
		for (int i = 0; ; i++) {
			if (i % 10 == 0)
				holder.refresh();
			if (i % 50 == 0)
				dispather.dispatch(0.0);
			holder.pick();
		}
	}
}
